<script setup>
import router from '@/router';
import { ElMessage } from 'element-plus'
import {ref, onMounted, onBeforeUnmount} from "vue";
import dayjs from "dayjs";
import {loginoutApi} from "@/api/login.js";
import {useUserStore} from "@/stores/user.js";

const userStore = useUserStore();
const time = ref()
const currentSchoolName = ref('河南工业和信息化职业学院')
let timeInterval = null

timeInterval = setInterval(() => {
  time.value = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
}, 1000)

onMounted(() => {
  time.value = dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss');
})

onBeforeUnmount(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
    timeInterval = null;
  }
})

// 退出登录
const loginout = async () => {
  let currentUserId = localStorage.getItem('currentUserId')
  if(!currentUserId || currentUserId == '') {
    ElMessage.error('用户未登录，请先登录')
    return await router.push('/login')
  }
  const res = await loginoutApi(currentUserId)
  if (res.code === 200) {
    // 清空用户数据和token
    userStore.clearUserInfo()
    userStore.clearToken()
    ElMessage.success('退出成功')
    await router.push('/login')
  } else {
    ElMessage.error(res.message)
  }
}
</script>

<template>
<div class="box">
    <!-- 顶部 -->
    <el-row>
        <el-col :span="12">
            <img src="@\assets\images\logo.png" height="30px" alt="">
        </el-col>
        <el-col :span="12">
            <div class="header-right">
                <el-icon><User /></el-icon>&nbsp;&nbsp;
                {{ currentSchoolName }}&nbsp;&nbsp;&nbsp;&nbsp;
                <a style="color: red;" @click.prevent="loginout">退出登录</a>
                &nbsp;&nbsp;{{ time }}
            </div>
        </el-col>
    </el-row>
    <!-- 导航栏部分 -->
    <el-row class="layout">
        <router-link to="/home">首页</router-link>
        <router-link to="/user">用户</router-link>
        <router-link to="/evaluation">心理评测</router-link>
        <router-link to="/intervention">预警干预</router-link>
        <router-link to="/consultation">咨询预约</router-link>
        <router-link to="/course">心理课程</router-link>
        <router-link to="/person">个人中心</router-link>
    </el-row>
    <!-- 导航栏导航的内容区 -->
    <div class="main">
        <router-view></router-view>
    </div>
</div>
</template>

<style scoped>
.box {
    width: 95%;
    margin: 0 auto;
}
.header-right {
    margin-top: 10px;
    margin-right: 0px;
    font-size: 15px;
    color: rgba(0, 0, 0, .5);
    text-align: right;
}
.layout {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
    background-color: white;
    font-size: 18px;
    color: #4fa1fb;
    border-radius: 4px;
}
.layout a {
  display: inline-block;
  padding: 6px 20px;
  border-radius: 6px;
  transition: all 0.3s ease;
  font-weight: 600;
}
.layout a:hover {
    background-color: #4fa1fb;
    color: white;
}
.layout .router-link-active {
    background-color: #4fa1fb;
    color: white;
}
.main {
    margin-top: 10px;
}
</style>
